import { useEffect, useState } from 'react'

// 设置页面标题
export function useTitle(title: string) {
  useEffect(() => {
    document.title = title
  }, [])
}

// 获取数据实时位置
export function useMousePosition() {
  // 初始化鼠标位置为当前鼠标位置
  const [x, setX] = useState(0)
  const [y, setY] = useState(0)

  useEffect(() => {
    function updateMousePosition(e: MouseEvent) {
      setX(e.clientX)
      setY(e.clientY)
    }

    document.addEventListener('mousemove', updateMousePosition)

    return () => {
      document.removeEventListener('mousemove', updateMousePosition)
    }
  }, [])

  return {
    x,
    y
  }
}

function getInfo(): Promise<string> {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Date.now().toString())
    }, 1500)
  })
}

// 模拟异步获取数据
export function useGetInfo() {
  const [loading, setLoading] = useState(true)
  const [userInfo, setUserInfo] = useState<string | null>(null)
  useEffect(() => {
    getInfo().then(info => {
      setLoading(false)
      setUserInfo(info)
    })
  }, [])
  return {
    loading,
    userInfo
  }
}
